package com.jumi.microservice.service.invoice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.common.exception.BaseException;
import com.jumi.microservice.common.page.TableDataInfo;
import com.jumi.microservice.common.utils.DateUtil;
import com.jumi.microservice.domain.GoodsShortNameInfoDTO;
import com.jumi.microservice.dto.apiService.OrderGoodsNumNameResponse;
import com.jumi.microservice.dto.invoice.*;
import com.jumi.microservice.entity.OrderGoods;
import com.jumi.microservice.mapper.OrderGoodsMapper;
import com.jumi.microservice.service.BasicDataService;
import com.jumi.microservice.service.CommodityApi;
import com.jumi.microservice.service.invoice.invoiceConfig.InvoiceConfig;
import com.jumi.microservice.utils.nuonuo.QueryThirdCommonRequest;
import com.jumi.microservice.utils.nuonuo.ThirdCommonParametersRequest;
import com.jumi.microservice.utils.nuonuo.ThirdPartyInvoiceDetailsRequest;
import com.jumi.microservice.utils.nuonuo.ThirdPartyInvoiceRequest;
import com.jumi.microservice.dto.reponse.JmUserReponse;
import com.jumi.microservice.entity.JumiInvoice;
import com.jumi.microservice.entity.JumiInvoiceList;
import com.jumi.microservice.enumerate.InvoiceStatusEnum;
import com.jumi.microservice.exception.InvoiceExceptionEnum;
import com.jumi.microservice.mapper.InvoiceListMapper;
import com.jumi.microservice.mapper.InvoiceMapper;
import com.jumi.microservice.service.IMemberService;
import com.jumi.microservice.service.IOrderGoodsService;
import com.jumi.microservice.service.order.OrderServiceImpl;
import com.jumi.microservice.utils.NuoNuoUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Administrator
 */
@Service
@RefreshScope
public class InvoiceApiService {
    private static final Logger log = LoggerFactory.getLogger(InvoiceApiService.class);
    @Resource
    private InvoiceMapper invoiceMapper;
    @Resource
    private InvoiceListMapper invoiceListMapper;
    @Resource
    private OrderServiceImpl orderService;
    @DubboReference
    IMemberService memberService;
    @DubboReference
    IOrderGoodsService iorderGoodsService;
    //    //企业税号
//    @Value("${invoice.ein}")
//    private String ein;
//    @Value("${invoice.identity}")
//    private String identity;
    @Autowired
    InvoiceConfig invoiceConfig;
    @Resource
    private OrderGoodsMapper orderGoodsMapper;
    @DubboReference
    BasicDataService basicDataService;
    @Resource
    NuoNuoUtil nuoNuoUtil;
    @DubboReference
    CommodityApi commodityApi;

    /**
     * 前段发票详情接口--图片页面
     *
     * @param invoiceApiRequest
     * @return
     */
    public InvoiceApiResponse invoiceApiView(InvoiceApiRequest invoiceApiRequest) {
        String orderSn = invoiceApiRequest.getOrderNum();
        log.debug("前段发票详情接口------【图片页面】:[{}]", JSON.toJSONString(orderSn));
        if (orderSn == null) {
            throw new BaseException(InvoiceExceptionEnum.ORDER_SN_ERROR.getCode(), InvoiceExceptionEnum.ORDER_SN_ERROR.getMessage());
        }
        QueryWrapper<JumiInvoice> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("order_num", orderSn);
        queryWrapper.eq("id", invoiceApiRequest.getOrderInvoiceId());
        queryWrapper.eq("is_revoke", 0);
        queryWrapper.orderByDesc("id");
        JumiInvoice invoice = invoiceMapper.selectOne(queryWrapper);
        log.debug("前段发票详情接口------【图片页面invoice】:[{}]", JSON.toJSONString(invoice));
        if (invoice == null) {
            throw new BaseException(InvoiceExceptionEnum.INVOICE_INFO_NULL.getCode(), InvoiceExceptionEnum.INVOICE_INFO_NULL.getMessage());
        }
        InvoiceApiResponse invoiceApiResponse = new InvoiceApiResponse();
        BeanUtils.copyProperties(invoice, invoiceApiResponse);
        invoiceApiResponse.setInvoicePicture(invoice.getInvoicePdf());
        invoiceApiResponse.setOrderInvoiceId(invoice.getId());
        return invoiceApiResponse;
    }

    /**
     * 前段发票状态列表
     *
     * @param invoiceApiRequest
     * @return
     */
    public TableDataInfo<InvoiceApiStatusResponse> invoiceListStatus(InvoiceApiRequest invoiceApiRequest) {
        String orderSn = invoiceApiRequest.getOrderNum();
        log.debug("前段发票详情接口------【前段发票状态列表】:[{}]", JSON.toJSONString(orderSn));
        if (orderSn == null) {
            throw new BaseException(InvoiceExceptionEnum.ORDER_SN_ERROR.getCode(), InvoiceExceptionEnum.ORDER_SN_ERROR.getMessage());
        }
        QueryWrapper<JumiInvoice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_num", orderSn);
        queryWrapper.orderByDesc("id");
        List<JumiInvoice> invoice = invoiceMapper.selectList(queryWrapper);
        log.debug("前段发票详情接口------【前段发票状态列表invoice】:[{}]", JSON.toJSONString(invoice));
        if (invoice == null) {
            throw new BaseException(InvoiceExceptionEnum.INVOICE_INFO_ERROR.getCode(), InvoiceExceptionEnum.INVOICE_INFO_ERROR.getMessage());
        }
        JumiInvoice invoice1 = invoice.get(invoice.size() - 1);
        Byte invoiceStatus = invoice1.getInvoiceStatus();
        List<InvoiceApiStatusResponse> result = new ArrayList<>();
        for (JumiInvoice invoice2 : invoice) {
            InvoiceApiStatusResponse invoiceApiStatusResponse2 = new InvoiceApiStatusResponse();
            BeanUtils.copyProperties(invoice2, invoiceApiStatusResponse2);
            result.add(invoiceApiStatusResponse2);
        }
        TableDataInfo<InvoiceApiStatusResponse> dataInfo = new TableDataInfo<>();
        dataInfo.setRows(result);
        return dataInfo;
    }

    /**
     * 根据订单编号查询发票列表----列表页
     *
     * @param invoiceOrderSnListRequest
     * @return
     */
    public TableDataInfo<InvoiceOrderSnListResponse> invoiceListOrder(InvoiceOrderSnListRequest invoiceOrderSnListRequest) {
        String orderSn = invoiceOrderSnListRequest.getOrderNum();
        if (orderSn == null) {
            throw new BaseException(InvoiceExceptionEnum.ORDER_SN_ERROR.getCode(), InvoiceExceptionEnum.ORDER_SN_ERROR.getMessage());
        }
        QueryWrapper<JumiInvoice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_num", orderSn);
        queryWrapper.orderByDesc("id");
        List<JumiInvoice> invoice = invoiceMapper.selectList(queryWrapper);
        log.debug("前段发票详情接口------【根据订单编号查询发票列表----列表页】:[{}]", JSON.toJSONString(invoice));
        if (invoice == null) {
            throw new BaseException(InvoiceExceptionEnum.INVOICE_INFO_NULL.getCode(), InvoiceExceptionEnum.INVOICE_INFO_NULL.getMessage());
        }
        List<InvoiceOrderSnListResponse> result = new ArrayList<>();
        for (JumiInvoice invoice2 : invoice) {
            InvoiceOrderSnListResponse invoiceOrderSnListResponse = new InvoiceOrderSnListResponse();
            BeanUtils.copyProperties(invoice2, invoiceOrderSnListResponse);
            invoiceOrderSnListResponse.setOrderInvoiceId(invoice2.getId());
            result.add(invoiceOrderSnListResponse);
        }
        TableDataInfo<InvoiceOrderSnListResponse> dataInfo = new TableDataInfo<>();
        dataInfo.setRows(result);
        return dataInfo;
    }

    /**
     * 根据订单发票id查询----订单发票详情页
     *
     * @param invoiceApiDetailRequest
     * @return
     */
    public InvoiceApiStatusResponse invoiceListDetails(InvoiceApiDetailRequest invoiceApiDetailRequest) {
        Integer id = invoiceApiDetailRequest.getOrderInvoiceId();
        if (id == null) {
            throw new BaseException(InvoiceExceptionEnum.INVOICE_RED_ERROR.getCode(), InvoiceExceptionEnum.INVOICE_RED_ERROR.getMessage());
        }
        QueryWrapper<JumiInvoice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        JumiInvoice invoice = invoiceMapper.selectOne(queryWrapper);
        if (invoice == null) {
            throw new BaseException(InvoiceExceptionEnum.INVOICE_INFO_NULL.getCode(), InvoiceExceptionEnum.INVOICE_INFO_NULL.getMessage());
        }
        Integer invoiceId = invoice.getInvoiceId();
        JumiInvoiceList invoiceListOne = null;
        if (invoiceId != null) {
            QueryWrapper<JumiInvoiceList> queryListWrapper = new QueryWrapper<>();
            queryListWrapper.eq("id", invoiceId);
            invoiceListOne = invoiceListMapper.selectOne(queryListWrapper);
        }
        InvoiceApiStatusResponse invoiceApiStatusResponse = new InvoiceApiStatusResponse();
        BeanUtils.copyProperties(invoice, invoiceApiStatusResponse);
        invoiceApiStatusResponse.setOrderId(invoice.getOrderId().toString());
        QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.lambda().eq(OrderGoods::getOrderNo, invoice.getOrderNum());
//        List<OrderGoods> orderGoods = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
//        BigDecimal returnCount = new BigDecimal(0);
//        for (OrderGoods orderGood : orderGoods) {
//            returnCount = returnCount.add(orderGood.getReturnPrice());
//        }
        invoiceApiStatusResponse.setInvoiceAmount(invoice.getInvoiceAmount());
        invoiceApiStatusResponse.setOrderInvoiceId(id);
        if (invoiceListOne == null || invoiceListOne.getIsDefault() == null) {
            invoiceApiStatusResponse.setIsDefault((byte) 0);
        } else {
            invoiceApiStatusResponse.setIsDefault(invoiceListOne.getIsDefault());
        }
        return invoiceApiStatusResponse;
    }

    public ResponseResult<String> invoice(InvoiceOneRequest request) {
        ResponseResult<String> responseResult = new ResponseResult<>();
        ThirdCommonParametersRequest<ThirdPartyInvoiceRequest> thirdPartyInvoiceRequestThirdCommonParametersRequest = new ThirdCommonParametersRequest<>();
        QueryWrapper<JumiInvoice> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(JumiInvoice::getOrderNum, request.getOrderNum()).orderByAsc(JumiInvoice::getId).last("limit 1");
        JumiInvoice invoice = invoiceMapper.selectOne(queryWrapper);
        log.info("实体类是[{}]", JSON.toJSONString(invoice));
        log.info("开票数据是:[{}]", JSON.toJSONString(invoice));
        ThirdPartyInvoiceRequest thirdPartyInvoiceRequest = new ThirdPartyInvoiceRequest();
        thirdPartyInvoiceRequest.setBuyername(invoice.getInvoiceTitle());
        Long uid = orderService.getUidByOrderNo(invoice.getOrderNum());
        ResponseResult<JmUserReponse> user = memberService.getMemberByUid(uid.intValue());
        //手机号
        thirdPartyInvoiceRequest.setPhone(user.getData().getMobile());
        thirdPartyInvoiceRequest.setChecker("刘新新");
        thirdPartyInvoiceRequest.setPayee("王亚群");
        thirdPartyInvoiceRequest.setTsfs("1");
        //地址
        thirdPartyInvoiceRequest.setAddress(invoice.getBusinessAddress());
        //银行卡号
        thirdPartyInvoiceRequest.setAccount(invoice.getBankAccount());
        thirdPartyInvoiceRequest.setOrderno(request.getOrderNum());
        thirdPartyInvoiceRequest.setInvoicedate(DateUtil.getTime(new Date()));
        thirdPartyInvoiceRequest.setClerk("任新玲");
        thirdPartyInvoiceRequest.setSaletaxnum(invoiceConfig.getEin());
        thirdPartyInvoiceRequest.setKptype("1");
        //发票明细
        List<ThirdPartyInvoiceDetailsRequest> thirdPartyInvoiceDetailsRequest = new ArrayList<>();
        List<String> orderGoods = new ArrayList<>();
        orderGoods.add(request.getOrderNum());
        List<OrderGoodsNumNameResponse> orderGoodsNumNameResponses = iorderGoodsService.getGoodsNamePrice(orderGoods);
        log.info("查询出来的发票明细是:[{}]", JSON.toJSONString(orderGoodsNumNameResponses));
        List<Integer> spuId = orderGoodsNumNameResponses.stream().map(OrderGoodsNumNameResponse::getSpuId).collect(Collectors.toList());
        List<Long> spuIdLong = JSONArray.parseArray(spuId.toString(), Long.class);
        Map<Long, BigDecimal> goodsTax = basicDataService.getGoodsTaxBySpuId(spuIdLong);
        List<GoodsShortNameInfoDTO> goodsShortNameInfo4Order = commodityApi.getGoodsShortNameInfo4Order(spuIdLong);
        Map<Long, String> goods = goodsShortNameInfo4Order.stream().collect(Collectors.toMap(GoodsShortNameInfoDTO::getSpuId, GoodsShortNameInfoDTO::getShortName));
        orderGoodsNumNameResponses.forEach(
                orderGoodsNumNameResponse -> {
                    ThirdPartyInvoiceDetailsRequest partyInvoiceDetailsRequest = new ThirdPartyInvoiceDetailsRequest();
                    partyInvoiceDetailsRequest.setGoodsname(goods.get(orderGoodsNumNameResponse.getSpuId().longValue()));
                    partyInvoiceDetailsRequest.setNum(orderGoodsNumNameResponse.getNum().toString());
                    partyInvoiceDetailsRequest.setPrice(orderGoodsNumNameResponse.getInvoicePrice().toString());
                    partyInvoiceDetailsRequest.setHsbz("1");
                    partyInvoiceDetailsRequest.setFphxz("0");
                    //税率
                    if (goodsTax.get(orderGoodsNumNameResponse.getSpuId().longValue()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).equals(new BigDecimal(0))) {
                        log.info("0税率");
                        partyInvoiceDetailsRequest.setLslbs("1");
                    } else {
                        log.info("0.13税率");
                        partyInvoiceDetailsRequest.setTaxrate("0.13");
//                        partyInvoiceDetailsRequest.setTaxrate(goodsTax.get(orderGoodsNumNameResponse.getSpuId().longValue()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).toString());
                    }
                    thirdPartyInvoiceDetailsRequest.add(partyInvoiceDetailsRequest);
                }
        );
        thirdPartyInvoiceRequest.setDetail(thirdPartyInvoiceDetailsRequest);
        thirdPartyInvoiceRequestThirdCommonParametersRequest.setIdentity(invoiceConfig.getIdentity());
        thirdPartyInvoiceRequestThirdCommonParametersRequest.setOrder(thirdPartyInvoiceRequest);
        String result = nuoNuoUtil.Invoice(thirdPartyInvoiceRequestThirdCommonParametersRequest);
        JSONObject response = JSON.parseObject(result);
        log.debug("开票返回结果是:" + response.getString("fpqqlsh"));
        invoice.setSerialNumber(response.getString("fpqqlsh"));
        invoice.setIsRevoke((byte) 0);
        invoice.setInvoiceStatus(InvoiceStatusEnum.STA_WAIT_BILLED.getCode().byteValue());
        invoiceMapper.updateById(invoice);

        return responseResult;
    }


    public ResponseResult<String> returnInvoice(InvoiceOneRequest request) {
        ResponseResult<String> responseResult = new ResponseResult<>();
        ThirdCommonParametersRequest<ThirdPartyInvoiceRequest> thirdPartyInvoiceRequestThirdCommonParametersRequest = new ThirdCommonParametersRequest<>();
        QueryWrapper<JumiInvoice> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(JumiInvoice::getOrderNum, request.getOrderNum()).orderByDesc(JumiInvoice::getId).last("limit 1");
        JumiInvoice invoice = invoiceMapper.selectOne(queryWrapper);
        log.info("实体类是[{}]", JSON.toJSONString(invoice));
        log.info("售后专用开票接口:[{}]", JSON.toJSONString(invoice));
        ThirdPartyInvoiceRequest thirdPartyInvoiceRequest = new ThirdPartyInvoiceRequest();
        thirdPartyInvoiceRequest.setBuyername(invoice.getInvoiceTitle());
        Long uid = orderService.getUidByOrderNo(invoice.getOrderNum());
        ResponseResult<JmUserReponse> user = memberService.getMemberByUid(uid.intValue());
        //手机号
        thirdPartyInvoiceRequest.setPhone(user.getData().getMobile());
        thirdPartyInvoiceRequest.setChecker("刘新新");
        thirdPartyInvoiceRequest.setPayee("王亚群");
        //地址
        thirdPartyInvoiceRequest.setAddress(invoice.getBusinessAddress());
        //银行卡号
        thirdPartyInvoiceRequest.setAccount(invoice.getBankAccount());
        thirdPartyInvoiceRequest.setOrderno(request.getOrderNum().concat(invoice.getId().toString()));
        thirdPartyInvoiceRequest.setInvoicedate(DateUtil.getTime(new Date()));
        thirdPartyInvoiceRequest.setClerk("任新玲");
        thirdPartyInvoiceRequest.setSaletaxnum(invoiceConfig.getEin());
        thirdPartyInvoiceRequest.setKptype("1");
        thirdPartyInvoiceRequest.setTsfs("1");
        //发票明细
        List<ThirdPartyInvoiceDetailsRequest> thirdPartyInvoiceDetailsRequest = new ArrayList<>();
        List<String> orderGoods = new ArrayList<>();
        orderGoods.add(request.getOrderNum());
        List<OrderGoodsNumNameResponse> orderGoodsNumNameResponses = iorderGoodsService.getGoodsNamePrice(orderGoods);
        List<Integer> spuId = orderGoodsNumNameResponses.stream().map(OrderGoodsNumNameResponse::getSpuId).collect(Collectors.toList());
        List<Long> spuIdLong = JSONArray.parseArray(spuId.toString(), Long.class);
        Map<Long, BigDecimal> goodsTax = basicDataService.getGoodsTaxBySpuId(spuIdLong);
        List<GoodsShortNameInfoDTO> goodsShortNameInfo4Order = commodityApi.getGoodsShortNameInfo4Order(spuIdLong);
        Map<Long, String> longStringMap = goodsShortNameInfo4Order.stream().collect(Collectors.toMap(GoodsShortNameInfoDTO::getSpuId, GoodsShortNameInfoDTO::getShortName));
        log.info("查询出来的发票明细是:[{}]", JSON.toJSONString(orderGoodsNumNameResponses));
        orderGoodsNumNameResponses.forEach(
                orderGoodsNumNameResponse -> {
                    ThirdPartyInvoiceDetailsRequest partyInvoiceDetailsRequest = new ThirdPartyInvoiceDetailsRequest();
                    partyInvoiceDetailsRequest.setGoodsname(longStringMap.get(orderGoodsNumNameResponse.getSpuId().longValue()));
                    partyInvoiceDetailsRequest.setNum(new BigDecimal(orderGoodsNumNameResponse.getNum()).toString());
                    partyInvoiceDetailsRequest.setPrice(orderGoodsNumNameResponse.getPrice().toString());
                    partyInvoiceDetailsRequest.setHsbz("1");
                    partyInvoiceDetailsRequest.setFphxz("0");
                    //税率
                    if (goodsTax.get(orderGoodsNumNameResponse.getSpuId().longValue()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).equals(new BigDecimal(0))) {
                        log.info("0税率");
                        partyInvoiceDetailsRequest.setLslbs("1");
                    } else {
                        log.info("0.13税率");
                        partyInvoiceDetailsRequest.setTaxrate("0.13");
//                        partyInvoiceDetailsRequest.setTaxrate(goodsTax.get(orderGoodsNumNameResponse.getSpuId().longValue()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).toString());
                    }
                    thirdPartyInvoiceDetailsRequest.add(partyInvoiceDetailsRequest);
                }
        );
        thirdPartyInvoiceRequest.setDetail(thirdPartyInvoiceDetailsRequest);
        thirdPartyInvoiceRequestThirdCommonParametersRequest.setIdentity(invoiceConfig.getIdentity());
        thirdPartyInvoiceRequestThirdCommonParametersRequest.setOrder(thirdPartyInvoiceRequest);
        log.info("售后开票json是[{}]", JSON.toJSONString(thirdPartyInvoiceRequestThirdCommonParametersRequest));
        String result = nuoNuoUtil.Invoice(thirdPartyInvoiceRequestThirdCommonParametersRequest);
        log.info("售后专用开票返回结果:[{}]" + result);
        JumiInvoice jumiInvoice = new JumiInvoice();
        BigDecimal price = new BigDecimal(0);
        for (OrderGoodsNumNameResponse orderGoodsNumNameRespons : orderGoodsNumNameResponses) {
            price = price.add(orderGoodsNumNameRespons.getPrice());
        }
        BeanUtils.copyProperties(invoice, jumiInvoice);
        jumiInvoice.setIsRevoke((byte) 0);
        jumiInvoice.setInvoiceStatus(InvoiceStatusEnum.STA_WAIT_BILLED.getCode().byteValue());
        jumiInvoice.setId(null);
        BigDecimal invoicePrice = new BigDecimal(0);
        for (OrderGoodsNumNameResponse orderGoodsNumNameRespons : orderGoodsNumNameResponses) {
            invoicePrice = invoicePrice.add(orderGoodsNumNameRespons.getPrice().multiply(new BigDecimal(orderGoodsNumNameRespons.getNum())));
        }
        jumiInvoice.setInvoiceAmount(invoicePrice);
        jumiInvoice.setOrderNum(request.getOrderNum());
        jumiInvoice.setRedSerialNumber("");
        jumiInvoice.setInvoicePdf("");
        jumiInvoice.setRedInvoicePdf("");
        JSONObject response = JSON.parseObject(result);
        jumiInvoice.setSerialNumber(response.getString("fpqqlsh"));
        int responseRow = invoiceMapper.insert(jumiInvoice);
        log.info("售后确认收货添加新的发票:[{}]", responseRow);
        return responseResult;
    }

    /**
     * 全部冲红
     *
     * @param request
     * @return
     */
    public void invoiceToAllVoid(QueryThirdCommonRequest request) {
        ThirdCommonParametersRequest<ThirdPartyInvoiceRequest> thirdPartyInvoiceRequestThirdCommonParametersRequest = new ThirdCommonParametersRequest<>();
        QueryWrapper<JumiInvoice> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(JumiInvoice::getOrderNum, request.getOrderno()).orderByDesc(JumiInvoice::getId).last("limit 1");
        log.info("订单编号是[{}]", request.getOrderno());
        JumiInvoice invoice = invoiceMapper.selectOne(queryWrapper);
        log.info("开红票数据:[{}]", JSON.toJSONString(invoice));
        ThirdPartyInvoiceRequest thirdPartyInvoiceRequest = new ThirdPartyInvoiceRequest();
        thirdPartyInvoiceRequest.setBuyername(invoice.getInvoiceTitle());
        Long uid = orderService.getUidByOrderNo(invoice.getOrderNum());
        ResponseResult<JmUserReponse> user = memberService.getMemberByUid(uid.intValue());
        //手机号
        thirdPartyInvoiceRequest.setPhone(user.getData().getMobile());
        thirdPartyInvoiceRequest.setChecker("刘新新");
        thirdPartyInvoiceRequest.setPayee("王亚群");
        //地址
        thirdPartyInvoiceRequest.setAddress(invoice.getBusinessAddress());
        //银行卡号
        thirdPartyInvoiceRequest.setAccount(invoice.getBankAccount());
        thirdPartyInvoiceRequest.setOrderno(request.getOrderno());
        thirdPartyInvoiceRequest.setInvoicedate(DateUtil.getTime(new Date()));
        thirdPartyInvoiceRequest.setClerk("任新玲");
        thirdPartyInvoiceRequest.setSaletaxnum(invoiceConfig.getEin());
        thirdPartyInvoiceRequest.setKptype("2");
        thirdPartyInvoiceRequest.setTsfs("-1");
        //发票明细
        List<ThirdPartyInvoiceDetailsRequest> thirdPartyInvoiceDetailsRequest = new ArrayList<>();
        List<String> orderGoods = new ArrayList<>();
        orderGoods.add(request.getOrderno());
        List<OrderGoodsNumNameResponse> orderGoodsNumNameResponses = iorderGoodsService.redInvoiceOrderList(orderGoods);
        log.info("查询出来的发票明细是:[{}]", JSON.toJSONString(orderGoodsNumNameResponses));
        QueryThirdCommonRequest queryThirdCommonRequest = new QueryThirdCommonRequest();
        queryThirdCommonRequest.setFpqqlsh(invoice.getSerialNumber());
        log.info("流水号是[{}]", invoice.getSerialNumber());
        queryThirdCommonRequest.setOfferInvoiceDetail(true);
        queryThirdCommonRequest.setIdentity(invoiceConfig.getIdentity());
        String queryInvoice = nuoNuoUtil.QueryInvoice(queryThirdCommonRequest);
        log.info("要冲红的发票数据是:[{}]", queryInvoice);
        JSONObject jsonObject = JSON.parseObject(queryInvoice);
        JSONArray list = jsonObject.getJSONArray("list");
        for (Object o : list) {
            thirdPartyInvoiceRequest.setFpdm(((JSONObject) o).getString("c_fpdm"));
            thirdPartyInvoiceRequest.setFphm(((JSONObject) o).getString("c_fphm"));
        }
        List<Integer> spuId = orderGoodsNumNameResponses.stream().map(OrderGoodsNumNameResponse::getSpuId).collect(Collectors.toList());
        List<Long> spuIdLong = JSONArray.parseArray(spuId.toString(), Long.class);
        Map<Long, BigDecimal> goodsTax = basicDataService.getGoodsTaxBySpuId(spuIdLong);
        List<GoodsShortNameInfoDTO> goodsShortNameInfo4Order = commodityApi.getGoodsShortNameInfo4Order(spuIdLong);
        Map<Long, String> longStringMap = goodsShortNameInfo4Order.stream().collect(Collectors.toMap(GoodsShortNameInfoDTO::getSpuId, GoodsShortNameInfoDTO::getShortName));
        orderGoodsNumNameResponses.forEach(
                orderGoodsNumNameResponse -> {
                    ThirdPartyInvoiceDetailsRequest partyInvoiceDetailsRequest = new ThirdPartyInvoiceDetailsRequest();
                    partyInvoiceDetailsRequest.setGoodsname(longStringMap.get(orderGoodsNumNameResponse.getSpuId().longValue()));
                    partyInvoiceDetailsRequest.setNum("-".concat(orderGoodsNumNameResponse.getNum().toString()));
                    partyInvoiceDetailsRequest.setPrice(orderGoodsNumNameResponse.getPrice().toString());
                    partyInvoiceDetailsRequest.setTaxamt(orderGoodsNumNameResponse.getPrice().negate().toString());
                    partyInvoiceDetailsRequest.setHsbz("1");
                    partyInvoiceDetailsRequest.setFphxz("0");
                    //税率
                    if (goodsTax.get(orderGoodsNumNameResponse.getSpuId().longValue()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).equals(new BigDecimal(0))) {
                        log.info("0税率");
                        partyInvoiceDetailsRequest.setLslbs("1");
                        partyInvoiceDetailsRequest.setTaxrate("0");
                    } else {
                        log.info("0.13税率");
                        partyInvoiceDetailsRequest.setTaxrate("0.13");
//                        partyInvoiceDetailsRequest.setTaxrate(goodsTax.get(orderGoodsNumNameResponse.getSpuId().longValue()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).toString());
                    }
                    thirdPartyInvoiceDetailsRequest.add(partyInvoiceDetailsRequest);
                }
        );
        thirdPartyInvoiceRequest.setDetail(thirdPartyInvoiceDetailsRequest);
        thirdPartyInvoiceRequestThirdCommonParametersRequest.setIdentity(invoiceConfig.getIdentity());
        thirdPartyInvoiceRequestThirdCommonParametersRequest.setOrder(thirdPartyInvoiceRequest);
        String result = nuoNuoUtil.Invoice(thirdPartyInvoiceRequestThirdCommonParametersRequest);
        log.info("开红票的数据是:[{}]", JSON.toJSONString(thirdPartyInvoiceRequestThirdCommonParametersRequest));
        log.info("开红票结果:" + JSON.parseObject(result));
        JSONObject response = JSON.parseObject(result);
        invoice.setRedSerialNumber(response.getString("fpqqlsh"));
        log.info("红票结果流水号是[{}]", response.getString("c_fpqqlsh"));
        invoice.setInvoiceStatus(InvoiceStatusEnum.STA_WAIT_REDDDMED.getCode().byteValue());
        log.info("红票添加到数据库的数据是[{}]", JSON.toJSONString(invoice));
        invoiceMapper.updateById(invoice);
    }

    /**
     * 部分商品冲红
     *
     * @param request
     */
    public void invoiceToVoid(InvoiceOrderRequest request) {
        ThirdCommonParametersRequest<ThirdPartyInvoiceRequest> thirdPartyInvoiceRequestThirdCommonParametersRequest = new ThirdCommonParametersRequest<>();
        QueryWrapper<JumiInvoice> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(JumiInvoice::getOrderNum, request.getOrderNo()).orderByDesc(JumiInvoice::getId).last("limit 1");
        log.info("订单编号是[{}]", request.getOrderNo());
        JumiInvoice invoice = invoiceMapper.selectOne(queryWrapper);
        log.info("开红票数据:[{}]", JSON.toJSONString(invoice));
        ThirdPartyInvoiceRequest thirdPartyInvoiceRequest = new ThirdPartyInvoiceRequest();
        thirdPartyInvoiceRequest.setBuyername(invoice.getInvoiceTitle());
        Long uid = orderService.getUidByOrderNo(invoice.getOrderNum());
        ResponseResult<JmUserReponse> user = memberService.getMemberByUid(uid.intValue());
        //手机号
        thirdPartyInvoiceRequest.setPhone(user.getData().getMobile());
        thirdPartyInvoiceRequest.setChecker("刘新新");
        thirdPartyInvoiceRequest.setPayee("王亚群");
        //地址
        thirdPartyInvoiceRequest.setAddress(invoice.getBusinessAddress());
        //银行卡号
        thirdPartyInvoiceRequest.setAccount(invoice.getBankAccount());
        thirdPartyInvoiceRequest.setOrderno(request.getOrderNo());
        thirdPartyInvoiceRequest.setInvoicedate(DateUtil.getTime(new Date()));
        thirdPartyInvoiceRequest.setClerk("任新玲");
        thirdPartyInvoiceRequest.setSaletaxnum(invoiceConfig.getEin());
        thirdPartyInvoiceRequest.setKptype("2");
        thirdPartyInvoiceRequest.setTsfs("-1");
        //发票明细
        List<ThirdPartyInvoiceDetailsRequest> thirdPartyInvoiceDetailsRequest = new ArrayList<>();
        OrderGoodsNumNameResponse orderGoodsNumNameResponses = iorderGoodsService.redInvoiceOrder(request.getOrderNo(), request.getGoodsId());
        log.info("查询出来的发票明细是:[{}]", JSON.toJSONString(orderGoodsNumNameResponses));
        QueryThirdCommonRequest queryThirdCommonRequest = new QueryThirdCommonRequest();
        queryThirdCommonRequest.setFpqqlsh(invoice.getSerialNumber());
        log.info("流水号是[{}]", invoice.getSerialNumber());
        queryThirdCommonRequest.setOfferInvoiceDetail(true);
        queryThirdCommonRequest.setIdentity(invoiceConfig.getIdentity());
        String queryInvoice = nuoNuoUtil.QueryInvoice(queryThirdCommonRequest);
        log.info("要冲红的发票数据是:[{}]", queryInvoice);
        JSONObject jsonObject = JSON.parseObject(queryInvoice);
        JSONArray list = jsonObject.getJSONArray("list");
        for (Object o : list) {
            thirdPartyInvoiceRequest.setFpdm(((JSONObject) o).getString("c_fpdm"));
            thirdPartyInvoiceRequest.setFphm(((JSONObject) o).getString("c_fphm"));
        }
        List<Long> spuIdLong = new ArrayList<>();
        spuIdLong.add(orderGoodsNumNameResponses.getSpuId().longValue());
        Map<Long, BigDecimal> goodsTax = basicDataService.getGoodsTaxBySpuId(spuIdLong);
        List<GoodsShortNameInfoDTO> goodsShortNameInfoDTOS = commodityApi.getGoodsShortNameInfo4Order(spuIdLong);
        Map<Long, String> longStringMap = goodsShortNameInfoDTOS.stream().collect(Collectors.toMap(GoodsShortNameInfoDTO::getSpuId, GoodsShortNameInfoDTO::getShortName));
        ThirdPartyInvoiceDetailsRequest partyInvoiceDetailsRequest = new ThirdPartyInvoiceDetailsRequest();
        partyInvoiceDetailsRequest.setGoodsname(longStringMap.get(orderGoodsNumNameResponses.getSpuId().longValue()));
        partyInvoiceDetailsRequest.setNum("-".concat(orderGoodsNumNameResponses.getNum().toString()));
        partyInvoiceDetailsRequest.setPrice(orderGoodsNumNameResponses.getPrice().toString());
        partyInvoiceDetailsRequest.setTaxamt(orderGoodsNumNameResponses.getPrice().negate().toString());
        partyInvoiceDetailsRequest.setHsbz("1");
        partyInvoiceDetailsRequest.setFphxz("0");
        //税率
        if (goodsTax.get(orderGoodsNumNameResponses.getSpuId().longValue()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).equals(new BigDecimal(0))) {
            log.info("0税率");
            partyInvoiceDetailsRequest.setLslbs("1");
            partyInvoiceDetailsRequest.setTaxrate("0");
        } else {
            log.info("0.13税率");
            partyInvoiceDetailsRequest.setTaxrate("0.13");
//            partyInvoiceDetailsRequest.setTaxrate(goodsTax.get(orderGoodsNumNameResponses.getSpuId().longValue()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).toString());
        }
        thirdPartyInvoiceDetailsRequest.add(partyInvoiceDetailsRequest);
        thirdPartyInvoiceRequest.setDetail(thirdPartyInvoiceDetailsRequest);
        thirdPartyInvoiceRequestThirdCommonParametersRequest.setIdentity(invoiceConfig.getIdentity());
        thirdPartyInvoiceRequestThirdCommonParametersRequest.setOrder(thirdPartyInvoiceRequest);
        String result = nuoNuoUtil.Invoice(thirdPartyInvoiceRequestThirdCommonParametersRequest);
        log.info("开红票的数据是:[{}]", JSON.toJSONString(thirdPartyInvoiceRequestThirdCommonParametersRequest));
        log.info("开红票结果:" + JSON.parseObject(result));
        JSONObject response = JSON.parseObject(result);
        invoice.setRedSerialNumber(response.getString("fpqqlsh"));
        log.info("红票结果流水号是[{}]", response.getString("c_fpqqlsh"));
        invoice.setInvoiceStatus(InvoiceStatusEnum.STA_WAIT_REDDDMED.getCode().byteValue());
        log.info("红票添加到数据库的数据是[{}]", JSON.toJSONString(invoice));
        invoiceMapper.updateById(invoice);
    }
}
